package db

import (
	"fmt"
	"gitee.com/baizhige/mongong-go/common"
	"go.mongodb.org/mongo-driver/mongo"
	"sync"
)

var dbPool = map[string]*mongo.Database{}

var collPool = map[string]*mongo.Collection{} //因为不好管理泛型 只好any了
var mutex = sync.Mutex{}

// 除了支持组合CollectionOperations.go实现数据交互 也支持直接传入泛型来搞

const DefaultDBKey = "default"

func InPool(key string, value *mongo.Database) {
	dbPool[key] = value
}

func InCollPoll(dbKey, collName string, value *mongo.Collection) {
	key := collKey(dbKey, collName)
	collPool[key] = value
}

func Collection(dbKey, collectionName string) (res *mongo.Collection, err error) {
	key := collKey(dbKey, collectionName)
	collection, ok := collPool[key]
	if !ok {
		mutex.Lock() //没找到 上个锁 准备初始化
		defer mutex.Unlock()
		if _, ok = collPool[key]; !ok {
			database, ok := dbPool[dbKey] //检查数据源对象是否存在
			if !ok {
				return nil, common.ErrDatabaseNotInit
			}

			//此处说明数据源存在 ， 但是第一次初始化集合对象
			collection = database.Collection(collectionName)
			collPool[key] = collection
		}
	}
	return collection, nil
}

func collKey(dbKey, collName string) string {
	return fmt.Sprintf("%s_%s", dbKey, collName)
}
